package com.cb2.algorithm.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <a href='https://leetcode.cn/problems/permutations-ii/'>全排列 II(Permutations II)</a>
 * <p>给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。</p>
 *
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：nums = [1,1,2]
 *      输出：
 *          [[1,1,2],
 *          [1,2,1],
 *          [2,1,1]]
 * 示例 2：
 *      输入：nums = [1,2,3]
 *      输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 * </pre>
 * </p>
 *
 * <p>
 * <b>提示：</b>
 *     <ul>
 *         <li>1 <= nums.length <= 8</li>
 *         <li>-10 <= nums[i] <= 10</li>
 *     </ul>
 * </p>
 *
 * @author c2b
 * @see LC0046Permutations_M 全排列(Permutations)
 * @see LC0047Permutations_II_M 全排列 II(Permutations II)
 * @since 2025/2/13 15:05
 */
public class LC0047Permutations_II_M {
    static class Solution {
        public List<List<Integer>> permuteUnique(int[] nums) {
            Arrays.sort(nums);  // 排序
            List<List<Integer>> resList = new ArrayList<>();
            boolean[] visited = new boolean[8]; // 题目限制
            backtracking(nums, visited, new ArrayList<>(), resList);
            return resList;
        }

        private void backtracking(int[] nums, boolean[] visited, List<Integer> path, List<List<Integer>> resList) {
            if (path.size() == nums.length) {
                resList.add(new ArrayList<>(path));
                return;
            }
            for (int currIdx = 0; currIdx < nums.length; currIdx++) {
                // 去重
                // used[i - 1] == true， 说明同一树枝nums[i - 1]使用过。可以继续选取
                // used[i - 1] == false，说明同一树层nums[i - 1]使用过。无法重复选取
                // 如果同一树层nums[i - 1]使用过则直接跳过
                if (currIdx > 0 && nums[currIdx] == nums[currIdx - 1] && !visited[currIdx - 1]) {
                    continue;
                }
                if (!visited[currIdx]) {
                    visited[currIdx] = true;
                    path.add(nums[currIdx]);
                    backtracking(nums, visited, path, resList);
                    visited[currIdx] = false;
                    path.remove(path.size() - 1);
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        Printer.printListListInteger(solution.permuteUnique(new int[]{1, 1, 2}));
        Printer.printListListInteger(solution.permuteUnique(new int[]{1, 2, 3}));
        Printer.printListListInteger(solution.permuteUnique(new int[]{1}));
    }
}
